import { Request, Response } from 'express';
import { ProductService } from '../services/productService';
import type { CreateProductRequest, UpdateProductRequest } from '../types/product';
import * as ExcelJS from 'exceljs';

const productService = new ProductService();

export class ProductController {
  // === 用户端接口 ===
  
  // 获取产品列表 (用户端)
  async getProducts(req: Request, res: Response) {
    try {
      const { page, pageSize, categoryId, sort, keyword } = req.query;
      
      const result = await productService.getProducts({
        page: page ? parseInt(page as string) : undefined,
        pageSize: pageSize ? parseInt(pageSize as string) : undefined,
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        sort: sort as 'latest' | 'popular' | undefined,
        keyword: keyword as string | undefined
      });

      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      console.error('获取产品列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品列表失败'
      });
    }
  }

  // 获取单个产品详情 (用户端)
  async getProductBySlug(req: Request, res: Response) {
    try {
      const { slug } = req.params;
      
      const product = await productService.getProductBySlug(slug);
      
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '产品不存在'
        });
      }

      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      console.error('获取产品详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品详情失败'
      });
    }
  }

  // 获取推荐产品 (用户端)
  async getRecommendProducts(req: Request, res: Response) {
    try {
      const { limit } = req.query;
      
      const products = await productService.getRecommendProducts(
        limit ? parseInt(limit as string) : 6
      );

      res.json({
        success: true,
        data: products
      });
    } catch (error) {
      console.error('获取推荐产品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取推荐产品失败'
      });
    }
  }

  // 获取置顶产品 (用户端)
  async getTopProducts(req: Request, res: Response) {
    try {
      const { limit } = req.query;
      
      const products = await productService.getTopProducts(
        limit ? parseInt(limit as string) : 6
      );

      res.json({
        success: true,
        data: products
      });
    } catch (error) {
      console.error('获取置顶产品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取置顶产品失败'
      });
    }
  }

  // 获取产品分类 (用户端)
  async getProductCategories(req: Request, res: Response) {
    try {
      const categories = await productService.getProductCategories();

      res.json({
        success: true,
        data: categories
      });
    } catch (error) {
      console.error('获取产品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品分类失败'
      });
    }
  }

  // === 管理端接口 ===

  // 获取产品列表 (管理端)
  async getAdminProducts(req: Request, res: Response) {
    try {
      const { page, pageSize, categoryId, status, keyword, userId, sort } = req.query;
      
      const result = await productService.getAdminProducts({
        page: page ? parseInt(page as string) : undefined,
        pageSize: pageSize ? parseInt(pageSize as string) : undefined,
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        status: status !== undefined ? status === 'true' : undefined,
        keyword: keyword as string | undefined,
        userId: userId ? parseInt(userId as string) : undefined,
        sort: sort as string | undefined
      });

      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      console.error('获取管理端产品列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品列表失败'
      });
    }
  }

  // 获取单个产品详情 (管理端)
  async getProductById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      
      const product = await productService.getProductById(parseInt(id));
      
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '产品不存在'
        });
      }

      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      console.error('获取产品详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品详情失败'
      });
    }
  }

  // 创建产品 (管理端)
  async createProduct(req: Request, res: Response) {
    try {
      const data: CreateProductRequest = req.body;
      const userId = (req as any).user?.id;

      if (!userId) {
        return res.status(401).json({
          success: false,
          message: '未授权'
        });
      }

      const product = await productService.createProduct(data, userId);

      res.status(201).json({
        success: true,
        data: product,
        message: '产品创建成功'
      });
    } catch (error) {
      console.error('创建产品失败:', error);
      res.status(500).json({
        success: false,
        message: '创建产品失败'
      });
    }
  }

  // 更新产品 (管理端)
  async updateProduct(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const data: UpdateProductRequest = req.body;

      const product = await productService.updateProduct(parseInt(id), data);

      res.json({
        success: true,
        data: product,
        message: '产品更新成功'
      });
    } catch (error) {
      console.error('更新产品失败:', error);
      res.status(500).json({
        success: false,
        message: '更新产品失败'
      });
    }
  }

  // 删除产品 (管理端)
  async deleteProduct(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const deleteBy = (req as any).user?.id; // 获取当前操作用户ID

      await productService.deleteProduct(parseInt(id), deleteBy);

      res.json({
        success: true,
        message: '产品删除成功'
      });
    } catch (error) {
      console.error('删除产品失败:', error);
      res.status(500).json({
        success: false,
        message: '删除产品失败'
      });
    }
  }

  // 获取产品统计 (管理端)
  async getProductStats(req: Request, res: Response) {
    try {
      const stats = await productService.getProductStats();

      res.json({
        success: true,
        data: stats
      });
    } catch (error) {
      console.error('获取产品统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品统计失败'
      });
    }
  }

  // === 产品分类管理 ===

  // 获取产品分类列表 (管理端)
  async getAdminProductCategories(req: Request, res: Response) {
    try {
      const categories = await productService.getAdminProductCategories();

      res.json({
        success: true,
        data: categories
      });
    } catch (error) {
      console.error('获取产品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品分类失败'
      });
    }
  }

  // 获取单个产品分类 (管理端)
  async getProductCategoryById(req: Request, res: Response) {
    try {
      const { id } = req.params;
      
      const category = await productService.getProductCategoryById(parseInt(id));
      
      if (!category) {
        return res.status(404).json({
          success: false,
          message: '产品分类不存在'
        });
      }

      res.json({
        success: true,
        data: category
      });
    } catch (error) {
      console.error('获取产品分类详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取产品分类详情失败'
      });
    }
  }

  // 创建产品分类 (管理端)
  async createProductCategory(req: Request, res: Response) {
    try {
      const data = req.body;

      const category = await productService.createProductCategory(data);

      res.status(201).json({
        success: true,
        data: category,
        message: '产品分类创建成功'
      });
    } catch (error) {
      console.error('创建产品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '创建产品分类失败'
      });
    }
  }

  // 更新产品分类 (管理端)
  async updateProductCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const data = req.body;

      const category = await productService.updateProductCategory(parseInt(id), data);

      res.json({
        success: true,
        data: category,
        message: '产品分类更新成功'
      });
    } catch (error) {
      console.error('更新产品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '更新产品分类失败'
      });
    }
  }

  // 删除产品分类 (管理端)
  async deleteProductCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;

      await productService.deleteProductCategory(parseInt(id));

      res.json({
        success: true,
        message: '产品分类删除成功'
      });
    } catch (error) {
      console.error('删除产品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '删除产品分类失败'
      });
    }
  }

  // 导出产品列表
  async exportProducts(req: Request, res: Response) {
    try {
      const {
        categoryId,
        status,
        keyword,
        userId,
        sort,
      } = req.query;

      // 获取所有符合条件的数据（不分页）
      const result = await productService.getAdminProducts({
        page: 1,
        pageSize: 10000, // 设置一个很大的数字来获取所有数据
        categoryId: categoryId ? parseInt(categoryId as string) : undefined,
        status: status !== undefined ? status === 'true' : undefined,
        keyword: keyword as string | undefined,
        userId: userId ? parseInt(userId as string) : undefined,
        sort: sort as string | undefined
      });

      const products = result.products;

      // 创建Excel工作簿
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('产品列表');

      // 设置列标题
      worksheet.columns = [
        { header: '产品名称', key: 'title', width: 30 },
        { header: '作者', key: 'author', width: 15 },
        { header: '创作者', key: 'creator', width: 15 },
        { header: '发布者', key: 'publisher', width: 15 },
        { header: '阅读数量', key: 'views', width: 12 },
        { header: '发布时间', key: 'publishedAt', width: 20 },
        { header: '创建时间', key: 'createdAt', width: 20 },
        { header: '状态', key: 'status', width: 10 },
        { header: '分类', key: 'category', width: 15 },
        { header: '置顶', key: 'isTop', width: 8 },
        { header: '推荐', key: 'isRecommend', width: 8 },
        { header: '官网链接', key: 'websiteUrl', width: 25 },
        { header: '开发者昵称', key: 'developerNickname', width: 15 },
      ];

      // 添加数据行
      products.forEach((product: any) => {
        worksheet.addRow({
          title: product.title,
          author: product.author,
          creator: product.user?.username || '未知',
          publisher: product.user?.username || '未知',
          views: product.views,
          publishedAt: product.publishedAt ? new Date(product.publishedAt).toLocaleString('zh-CN') : '未发布',
          createdAt: new Date(product.createdAt).toLocaleString('zh-CN'),
          status: product.status ? '已发布' : '草稿',
          category: product.category?.name || '未分类',
          isTop: product.isTop ? '是' : '否',
          isRecommend: product.isRecommend ? '是' : '否',
          websiteUrl: product.websiteUrl || '',
          developerNickname: product.developerNickname || '',
        });
      });

      // 设置表头样式
      worksheet.getRow(1).font = { bold: true };
      worksheet.getRow(1).fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE6E6FA' },
      };

      // 生成文件名
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0];
      const fileName = `产品列表_${dateStr}.xlsx`;

      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);

      // 写入响应流
      await workbook.xlsx.write(res);
      res.end();
    } catch (error) {
      console.error('导出产品失败:', error);
      res.status(500).json({
        success: false,
        message: '导出产品失败',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  }
} 